package com.glory.brepda.activity.check;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.CheckQueryListAdapter;
import com.glory.brepda.adapter.PmsEqpHisListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.entity.CheckSheetEntity;
import com.glory.brepda.entity.EqpInfoEntity;
import com.glory.brepda.entity.PmsEqpHis;
import com.glory.brepda.entity.PmsEqpHisEntity;
import com.glory.brepda.entity.SheetInfoEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.datepicker.CustomDatePicker;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class EqpPmsHisActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etEqpWork)
    FreeUI_ClearEditText etEqpWork;
    @BindView(R.id.tvRepairID)
    TextView tvRepairID;
    @BindView(R.id.tvRepairType)
    TextView tvRepairType;
    @BindView(R.id.tvPositionAndJobNo)
    TextView tvPositionAndJobNo;
    @BindView(R.id.rvCheckInfoList)
    RecyclerView rvCheckInfoList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvBeginTime)
    TextView tvBeginTime;
    @BindView(R.id.ivBeginTimeArrow)
    ImageView ivBeginTimeArrow;
    @BindView(R.id.flBeginTimeList)
    FrameLayout flBeginTimeList;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;
    @BindView(R.id.ivEndTimeArrow)
    ImageView ivEndTimeArrow;
    @BindView(R.id.flEndTimeList)
    FrameLayout flEndTimeList;
    @BindView(R.id.fldCheckList)
    FrameLayout fldCheckList;
    @BindView(R.id.tvDCheck)
    TextView tvDCheck;
    @BindView(R.id.ivDCheckArrow)
    ImageView ivDCheckArrow;

    private PmsEqpHisListAdapter mAdapter;
    private String mEqpType;
    private String mLocation;
    private String mSelectorStr = "ALL";
    private String beginDate;
    private String endDate;
    private CustomDatePicker mDatePicker;
    boolean isBegin;
    private FreeUI_GeneralPop codePop;
    private final List<String> city = new ArrayList<>(Arrays.asList("日检","周检","月检","季检","半年检","年检","不限类型"));

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_eqp_pms_his;
    }

    @Override
    protected void initView() {
        setMainLayout(llMain);
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        tvBaseSubmit.setText("查询");
        initRecyclerView(rvCheckInfoList,this);
        mAdapter = new PmsEqpHisListAdapter(null);
        mAdapter.isFirstOnly(true);
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        rvCheckInfoList.setAdapter(mAdapter);

        initDatePicker();
        beginDate = FreeApi_DateUtils.getAfterStringDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd", -3);
        tvBeginTime.setText(beginDate);
        endDate = FreeApi_DateUtils.getAfterStringDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd", 7);
        tvEndTime.setText(endDate);


//        initEdit(etEqpWork, s -> LotUtils.searchEqpInfo(s, EqpPmsHisActivity.this, getSupportFragmentManager(), new LotUtils.netCallback<EqpInfoEntity>() {
//            @Override
//            public void onSuccess(EqpInfoEntity response) {
//                if (response.getEQUIPMENT() != null) {
//                    mEqpType = response.getEQUIPMENT().getEQPTYPE();
//                    mLocation = response.getEQUIPMENT().getLOCATION();
//                }
//            }
//
//            @Override
//            public void onFail(Throwable t) {
//                loadError(t,"EQPQUERY");
//            }
//        }));

//        mAdapter.setOnCheckListener(item -> {
//            if (item.getRESERVED3().equals("Open")){
//                Bundle bundle = new Bundle();
//                bundle.putString("EQPID",item.getEQUIPMENTID());
//                bundle.putString("OBJECTRRN",item.getOBJECTRRN());
//                if (item.getGROUP1().equals("巡检")){
//                    if (actionControl("CheckInspectionActivity")){
//                        return;
//                    }
//                    FreeApi_Utils.skipWithExtraIntent("header",bundle,this,CheckInspectionActivity.class);
//                }else {
//                    if (actionControl("NewCheckTableActivity")){
//                        return;
//                    }
//                    FreeApi_Utils.skipWithExtraIntent("header",bundle,this,NewCheckTableActivity.class);
//                }
//
//            }else {
//                FreeApi_ToastUtils.showFreeToast("当前状态不允许",this,false,0);
//            }
//        });

        // ①组件监听的方式
        fldCheckList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (codePop != null) {
                    if (codePop.isShowing()) {
                        codePop.dismiss();
                    }
                } else {
                    codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), fldCheckList.getWidth(), city, ivDCheckArrow, (ty, i) -> {
                        tvDCheck.setText(ty);
//                        Toast.makeText(getApplicationContext(),ty,Toast.LENGTH_SHORT).show();
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivDCheckArrow);
                codePop.showAsDropDown(fldCheckList, 0, 0);
            }
        });
    }

    @OnClick({R.id.tvBaseSubmit,R.id.flBeginTimeList, R.id.flEndTimeList})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
//                if (actionControl("Submit28"))
//                    return;

                if (getText(etEqpWork).equals("")){
                    showToast("请扫描设备编号",false);
                    return;
                }
                requestData();
                break;
            case R.id.flBeginTimeList:
                isBegin = true;
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.flEndTimeList:
                isBegin = false;
                mDatePicker.show(System.currentTimeMillis());
                break;
        }
    }

    @Override
    protected void initData() {

    }

    private void requestData() {
        FreeUI_EntityCallBack<BaseResponseBean<PmsEqpHis>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<PmsEqpHis>>
                (new TypeToken<BaseResponseBean<PmsEqpHis>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<PmsEqpHis>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<PmsEqpHisEntity> sheetlist = response.body().getResponse().getBody().getPMSLIST();
                    if (sheetlist.size() <= 0){
                        showConfirmDialog("暂无数据");
                    }
                    mAdapter.setNewData(sheetlist);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<PmsEqpHis>> response) {
                super.onError(response);
                loadError(response.getException(),"CHECKSHEETQUERY");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID",getText(etEqpWork));
        map.addProperty("ACTIONTYPE","QUERYByDType");
        map.addProperty("startTime", beginDate);
        map.addProperty("endTime", endDate);
        map.addProperty("dType",tvDCheck.getText().toString());
        NetUtils.requestPostNet("IF.CHECKSHEETQUERY","Common",EqpPmsHisActivity.this,map,callBack);
    }

//    private List<SheetInfoEntity> getData( List<PmsEqpHisEntity> sheetlist) {
//        List<SheetInfoEntity> list = new ArrayList<>();
//        switch (mSelectorStr){
//            case "ALL":
//                list = sheetlist;
//                break;
//            case "SINGLE":
//                for (SheetInfoEntity entity : sheetlist){
//                    if (entity.getEQUIPMENTID().equals(getText(etEqpWork))){
//                        list.add(entity);
//                    }
//                }
//                break;
//            case "LOCATION":
//                for (SheetInfoEntity entity : sheetlist){
//                    if (entity.getRESERVED1().equals(mLocation)){
//                        list.add(entity);
//                    }
//                }
//                break;
//            case "EQPTYPE":
//                for (SheetInfoEntity entity : sheetlist){
//                    if (entity.getEQUIPMENTTYPE().equals(mEqpType)){
//                        list.add(entity);
//                    }
//                }
//                break;
//        }
//        listSort(list);
//        return list;
//    }

    private void listSort(List<SheetInfoEntity> list) {
        Collections.sort(list, (sheetInfoEntity, t1) -> {
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            try {
                Date dt1 = format.parse(sheetInfoEntity.getCHECKDATE());
                Date dt2 = format.parse(t1.getCHECKDATE());
                if (dt1.getTime() < dt2.getTime()) {
                    return 1;
                } else if (dt1.getTime() > dt2.getTime()) {
                    return -1;
                } else {
                    return 0;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 0;
        });
    }

    private void initDatePicker() {
        long beginTimestamp = FreeApi_DateUtils.str2Long("1992-03-20", false);
        long endTimestamp = FreeApi_DateUtils.str2Long("2222-02-22", false);

        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(this, timestamp -> {
            if (isBegin) {
                beginDate = FreeApi_DateUtils.long2Str(timestamp, false);
                tvBeginTime.setText(beginDate);
            } else {
                endDate = FreeApi_DateUtils.long2Str(timestamp, false);
                tvEndTime.setText(endDate);
            }

        }, beginTimestamp, endTimestamp);
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker.setCancelable(true);
        // 不显示时和分
        mDatePicker.setCanShowPreciseTime(false);
        // 不允许循环滚动
        mDatePicker.setScrollLoop(false);
        // 不允许滚动动画
        mDatePicker.setCanShowAnim(false);
    }

}